package com.nine.shop.controller;

import com.nine.shop.common.ServerResponse;
import com.nine.shop.model.Cart;
import com.nine.shop.model.Goods;
import com.nine.shop.model.Order;
import com.nine.shop.service.CartService;
import com.nine.shop.service.GoodsService;
import com.nine.shop.service.OrderService;
import com.nine.shop.utils.JsonUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;


/**
 * @Auther: wangcong
 * @Date: 2019/8/25 10:05
 * @Description:
 */
@RestController
@RequestMapping("api/shopping/shopcart")
public class CartController extends BaseController {
    @Resource
    private CartService cartService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private OrderService orderService;

    /**
     * @Description 查看购物车
     * @Param []
     * @Return com.nine.shop.common.ServerResponse
     * @Author wangcong
     * @Date 2019/8/25
     * @Time 10:34
     */
    @CrossOrigin
    @RequestMapping(value = "/searchshopcart.do", method = RequestMethod.POST)
    public ServerResponse searchShopcart() {
        //TODO 张新飞的代码
        return cartService.searchShopcart(getUser());


        //TODO 原来的代码
//        int userId = super.getUser().getId();
//        List<Cart> cartList = cartService.searchById(userId);
//        if (cartList==null||cartList.size()==0){
//            return ServerResponse.createByErrorMsg("购物车内无产品，去逛逛吧！");
//        }
//        return ServerResponse.createBySuccess(cartList);
    }

    /**
     * @Description 更新购物车信息
     * @Param [goodsId, amount]
     * @Return com.nine.shop.common.ServerResponse
     * @Author wangcong
     * @Date 2019/8/25
     * @Time 14:06
     */
    @CrossOrigin
    @RequestMapping("/updategoodsinfo.do")
    public ServerResponse updateGoodsInfo(int goodsId, int amount) {
        int userId = super.getUser().getId();
        if (amount > goodsService.getStock(goodsId)) {
            return ServerResponse.createByErrorMsg("库存不足");
        }
        if (amount < 0) {
            return ServerResponse.createByErrorMsg("参数错误！");
        }
        Cart cart = new Cart();
        cart.setGoodsId(goodsId);
        cart.setUserId(userId);
        cart.setAmount(amount);
        if (cartService.updategoodsinfo(cart)) {
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByErrorMsg("更新失败");


    }

    /**
     * 按cartid删除一个购物车商品
     *
     * @param cartid
     * @return
     */
    @RequestMapping(value = "/deletegoodsbyid.do", method = RequestMethod.POST)
    public ServerResponse deleteorderbyid(@RequestParam(name = "cartid") Integer cartid) {
        int a = cartService.deletegoodsbyid(cartid);
        if (a < 1) {
            return ServerResponse.createByErrorMsg("删除失败,没有该商品");
        }
        return ServerResponse.createBySuccessMsg("删除成功");
    }

    /**
     * @Description 提交订单
     * @Param [goodsList]
     * @Return com.nine.shop.common.ServerResponse
     * @Author wangcong
     * @Date 2019/8/25
     * @Time 15:03
     */
    //String goodslist= "[{\"goodsid\":\"3\",\"amount\":\"3\",\"cost\":\"3\"},{\"goodsid\":\"3\",\"amount\":\"3\",\"cost\":\"3\"},{\"goodsid\":\"3\",\"amount\":\"3\",\"cost\":\"3\"}]";
    @CrossOrigin
    @RequestMapping("/submitorder.do")
    public ServerResponse submitOrder(@RequestParam(name = "goodslist") String goodslist) {
        List orderList = JsonUtil.str2obj(goodslist, List.class);
        //获取goodslist 包含goodsid和amount和cost
        int userId = super.getUser().getId();
        if (orderList.isEmpty()) {
            return ServerResponse.createByErrorMsg("请选择商品后再提交！");
        }
        for (int i = 0; i < orderList.size(); i++) {
            //购物车信息
            LinkedHashMap map = (LinkedHashMap) orderList.get(i);
            Order order = new Order();
            order.setGoodsId((int) map.get("goodsid"));
            order.setAmount((int) map.get("amount"));
            order.setUserId(userId);
            order.setStatus(0);//未支付
            //判断价格是什么类型
//            if ()
//            String price_string = map.get("price").toString();
//            Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
//
//            if (pattern.matcher(price_string).matches()) {
//                //是Double类型
//                order.setCost(Integer.valueOf((int) map.get("amount")) * (Double) map.get("price"));
//            } else {
//                order.setCost(Integer.valueOf((int) map.get("amount")) * Double.valueOf((int) map.get("price")));
//            }
            order.setCost(Integer.valueOf((int) map.get("amount")) * Double.valueOf( (String) map.get("price")));
//            order.setCost(Integer.valueOf((int) map.get("amount")) * Double.valueOf((int) map.get("price")));
            order.setCreateDate(new java.util.Date());
            orderService.insertToOrede(order);
            //库存减少
            int stockNew = goodsService.getStock(order.getGoodsId()) - order.getAmount();
            Goods goods = new Goods();
            goods.setPrice(Double.valueOf( (String) map.get("price")));
            goods.setId(order.getGoodsId());
            goods.setCount(stockNew);
            goodsService.updateById(goods);
            //购物车清空
            cartService.clearnCart(userId, order.getGoodsId());
        }

        return ServerResponse.createBySuccess();

    }

}
